#include "core_buff.h"

CoreBuff::CoreBuff(int size):buff(nullptr)
{
	this->pos = 0;
	this->initsize = size;
	this->buffsize = size;
	this->buff = new char[this->initsize];
}


CoreBuff::~CoreBuff()
{
	if (this->buff)
	{
		delete[] this->buff;
	}
	this->buff = nullptr;
}

char* CoreBuff::getBuff()
{
	return this->buff;
}

int CoreBuff::getBuffSize()
{
	return this->buffsize;
}

int CoreBuff::getPos()
{
	return this->pos;
}

void CoreBuff::addPos(int add)
{
	this->pos += add;
}

int CoreBuff::getLastSize()
{
	return this->buffsize - this->pos;
}

void CoreBuff::push(const char* data, int len)
{
	int need = this->pos + len;
	int tmpsize = this->buffsize;
	if (need > tmpsize)
	{
		while (need > tmpsize)
		{
			tmpsize *= 2;
		}
		char* tmpbuff = new char[tmpsize];
		memcpy(tmpbuff, this->buff, this->pos);
		delete[] this->buff;
		this->buff = tmpbuff;
		this->buffsize = tmpsize;
	}
	int last = this->buffsize - this->pos;
	if (last >= len)
	{
		memcpy(this->buff + this->pos,data,len);
		this->pos += len;
	}
}

void CoreBuff::pop(int len)
{
	if (this->pos >= len)
	{
		memcpy(this->buff, this->buff + len, this->pos - len);
		this->pos -= len;
	}
	if (this->buffsize > this->initsize)
	{
		int tmpsize = this->buffsize;
		while (this->pos < tmpsize / 2 && tmpsize / 2 > this->initsize)
		{
			tmpsize = tmpsize / 2;
		}
		char* tmpbuff = new char[tmpsize];
		memcpy(tmpbuff, this->buff, this->pos);
		delete[] this->buff;
		this->buff = tmpbuff;
		this->buffsize = tmpsize;
	}
}



